package com.example.noteshare;

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import com.example.noteshare.Utilities.Constants;
import com.example.noteshare.Utilities.Repo;
import com.example.noteshare.asyncTasks.AsyncPost;
import com.example.noteshare.gson.LoginResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LogInPage extends Activity implements OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_log_in_page);
		Button btnLogin = (Button) this.findViewById(R.id.login_button);
		btnLogin.setOnClickListener(this);
		TextView newAccount = (TextView) this.findViewById(R.id.txtLogin);
		newAccount.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_button:
			
			//get the username and password
			EditText userid = (EditText) findViewById(R.id.username);
			EditText password = (EditText) findViewById(R.id.password);
			String usr = userid.getText().toString();
			String pass = password.getText().toString();

			//put them in a map
			Map<String, String> params = new HashMap<String, String>();
			params.put("username", usr);
			params.put("password", pass);

			//create the async task
			AsyncPost async = new AsyncPost(Constants.serverIP
					+ Constants.login, params);
			
			//get the results
			String result = "{}";
			try {
				result = async.execute().get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			
			//parse tje results
			Gson gson = new GsonBuilder().create();
			LoginResult lr = gson.fromJson(result, LoginResult.class);
			
			//see if login was successful
			Boolean successful;
			try{
				successful = Boolean.parseBoolean(lr.getSuccessful());
			}catch(Exception e){
				successful = false;
			}
            
			//if successful move to main menu
			if(successful){
				Repo.userId = lr.getId();
				Intent i = new Intent(LogInPage.this, MenuPage.class);
				startActivity(i);
			}else{
				Toast.makeText(getApplicationContext(), "Failed to login", Toast.LENGTH_LONG).show();
			}

			
			break;
		case R.id.txtLogin:
			Intent j = new Intent(LogInPage.this, AccountCreationPage.class);
			startActivity(j);
			break;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.log_in_page, menu);
		return true;
	}

}